package com.jarchie.htgl.fragment.contract;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coder.zzq.smartshow.toast.SmartToast;
import com.jarchie.htgl.R;
import com.jarchie.htgl.activity.ApproveDetailActivity;
import com.jarchie.htgl.adapter.MyListAdapter;
import com.jarchie.htgl.base.BaseApp;
import com.jarchie.htgl.base.BaseFragment;
import com.jarchie.htgl.bean.ApproveListBean;
import com.jarchie.htgl.constants.ConfigConstant;
import com.jarchie.htgl.event.RefreshEvent;
import com.jarchie.htgl.network.Api;
import com.jarchie.htgl.utils.LogUtil;
import com.jarchie.htgl.utils.RefreshInitView;
import com.jarchie.htgl.views.DialogLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Jarchie on 2018\1\4.
 * 创建未审批模块的页面
 */

public class ApproveNoFragment extends BaseFragment implements OnRefreshListener, OnLoadmoreListener {

    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private LinearLayout exceptionLayout;
    private TextView tipsMessage;
    private List<ApproveListBean.INFOBean> mList = new ArrayList<>();
    private ApproveListBean bean;
    private MyListAdapter mAdapter;
    private int pageNumber = 0; //页码

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_no_approve;
    }

    @Override
    protected void initView(View rootView) {
        mRefreshLayout = obtainView(R.id.refreshLayout);
        mRecyclerView = obtainView(R.id.approve_recycle);
        exceptionLayout = obtainView(R.id.exception_layout);
        tipsMessage = obtainView(R.id.tv_exception);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        RefreshInitView.initView(mRefreshLayout);
        EventBus.getDefault().register(this); //注册成为订阅者
    }

    @Override
    protected void setListener() {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadmoreListener(this);
    }

    @Override
    protected void initData() {
        RefreshInitView.initDataView(mRefreshLayout, getActivity());
        requestData(0, ConfigConstant.PAGING_INIT); //初始化数据
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) { //刷新数据
        mRefreshLayout.finishRefresh();
        requestData(0, ConfigConstant.PAGING_REFRESH);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) { //加载数据
        mRefreshLayout.finishLoadmore();
        requestData(pageNumber, ConfigConstant.PAGING_LOADMORE);
    }

    //网络请求数据
    private void requestData(int pageNum, final String flag) {
        this.pageNumber = pageNum;
        pageNumber++;
        if (flag.equals(ConfigConstant.PAGING_INIT)) {
            DialogLoader.show(getContext());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageNumber", pageNumber);
        map.put("pageSize", ConfigConstant.PAGE_SIZE);
        map.put("yhm", BaseApp.getInstance().getUserLogin().getINFO().get(0).getYhm());
        map.put("xm", BaseApp.getInstance().getUserLogin().getINFO().get(0).getXm());
        map.put("jsdm", BaseApp.getInstance().getUserLogin().getINFO().get(0).getJsdm());
        map.put("bmdm", BaseApp.getInstance().getUserLogin().getINFO().get(0).getBmdm());
        map.put("gsdm", BaseApp.getInstance().getUserLogin().getINFO().get(0).getGsdm());
        Api.getInstance().requestApproveList(map).enqueue(new Callback<ApproveListBean>() {
            @Override
            public void onResponse(@NonNull Call<ApproveListBean> call, @NonNull Response<ApproveListBean> response) {
                if (response.isSuccessful()) {
                    if (response.body().getMSG().equals(ConfigConstant.SUCCESS)) {
                        bean = response.body();
                        if (bean.getINFO().size() > 0) { //数据大于0时
                            if (flag.equals(ConfigConstant.PAGING_INIT)) { //初始化数据时
                                DialogLoader.dismiss();
                                mList.addAll(bean.getINFO());
                                mAdapter = new MyListAdapter(getContext(), mList);
                                mRecyclerView.setAdapter(mAdapter);
                            } else { //下拉刷新和上拉加载时
                                if (flag.equals(ConfigConstant.PAGING_REFRESH)) {
                                    mList.clear();
                                }
                                mList.addAll(bean.getINFO());
                                mAdapter.notifyDataSetChanged();
                            }
                            //Item的点击事件
                            mAdapter.setOnItemClickListener(new MyListAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(int position) {
                                    Intent intent = new Intent(getContext(), ApproveDetailActivity.class);
                                    intent.putExtra("detail",mList.get(position));
                                    intent.putExtra("page",ConfigConstant.PAGE_INTENT_NO);
                                    startActivity(intent);
                                }
                            });
                        } else { //无更多数据时
                            if (flag.equals(ConfigConstant.PAGING_LOADMORE)) {
                                SmartToast.showInCenter(getString(R.string.tips_no_more_data));
                                if (pageNumber > 1) {
                                    pageNumber--;
                                }
                            } else {
                                DialogLoader.dismiss();
                                mRefreshLayout.setVisibility(View.GONE);
                                exceptionLayout.setVisibility(View.VISIBLE);
                                tipsMessage.setText(getString(R.string.tips_no_data));
                            }
                        }
                    } else if (response.body().getMSG().equals(ConfigConstant.ERROR)) {
                        DialogLoader.dismiss();
                        SmartToast.showInCenter(getString(R.string.tips_error_data));
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<ApproveListBean> call, @NonNull Throwable t) {
                DialogLoader.dismiss();
                LogUtil.e(getString(R.string.tips_failure_data));
            }
        });
    }

    //订阅方法，当接收到这个事件时会调用这个方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(RefreshEvent event){
        if (event.getMessage().equals(ConfigConstant.PAGING_REFRESH)){
            mRefreshLayout.autoRefresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); //取消注册
    }

}
